<template>
  <router-view v-if="route.matched.length === 3" />
  <div v-else>
    <a-spin :spinning="loading">
      <search-box :show-search="false" :show-reset="false" @search="handleSearch" @reset="handleReset">
        <div style="position: relative">
          <div style="display: flex; flex-wrap: wrap; align-content: space-around">
            <div class="search-item">
              <div class="search-text">Client Name</div>
              <a-input v-model:value="searchStruct.clientName" />
            </div>
            <div class="search-item">
              <div class="search-text">Country/Region</div>
              <e-country-region-select v-model="countryIDWrapped" :allow-clear="true" />
            </div>
            <div class="search-item">
              <div class="search-text">URL</div>
              <a-input v-model:value="searchStruct.url" />
            </div>
            <div class="search-item">
              <div class="search-text">Authority</div>
              <a-select
                ref="select"
                v-model:value="authorityValue"
                show-search
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                option-label-prop="label"
                @change="handleChangeAuthority"
              >
                <a-select-option key="-1:-1" label="All"> All </a-select-option>
                <a-select-option
                  v-for="item in authorities.filter(authority => authority.type === 2)"
                  :key="item.id + ':2'"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
                <a-select-option
                  v-for="item in authorities.filter(authority => authority.type === 1)"
                  :key="item.id + ':1'"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </div>
            <div class="search-item">
              <div class="search-text">Owner</div>
              <a-select
                ref="select"
                v-model:value="searchStruct.empID"
                show-search
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                option-label-prop="label"
              >
                <a-select-option :key="-1" label="All"> All </a-select-option>
                <a-select-option v-for="item in owners" :key="item.id" :label="item.displayName">
                  {{ item.displayName }}
                </a-select-option>
              </a-select>
            </div>
            <div class="search-item">
              <div class="search-text">From</div>
              <a-date-picker
                v-model:value="searchStruct.beginTime"
                :disabled-date="disabledDateStart"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
            <div class="search-item">
              <div class="search-text">To</div>
              <a-date-picker
                v-model:value="searchStruct.endTime"
                :disabled-date="disabledDateEnd"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
            <div v-if="hasSalesPermission" class="search-item">
              <div class="search-text">All Sales</div>
              <a-input v-model:value="searchStruct.ownerBy" />
            </div>
            <div style="width: 100px; height: 62px"></div>
          </div>
          <a-space class="buttons" style="position: absolute; right: 0; bottom: 0">
            <a-button @click="handleReset">Reset</a-button>
            <a-button class="secondary" @click="handleSearch">Search</a-button>
          </a-space>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Phase Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="phase in filter.clientPhaseLists"
              :key="phase.id"
              v-model="phase.checked"
              @change="handleFilterChange.phase[phase.phaseName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ phase.count }}</span> {{ phase.phaseName }}
            </e-checkbox>
          </div>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Status Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="status in filter.clientStatusLists"
              :key="status.id"
              v-model="status.checked"
              @change="handleFilterChange.status[status.statusName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ status.count }}</span> {{ status.statusName }}
            </e-checkbox>
          </div>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Client Tier Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="tier in filter.clientTierLists"
              :key="tier.id"
              v-model="tier.checked"
              @change="handleFilterChange.tier[tier.tierName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ tier.count }}</span> {{ tier.tierName }}
            </e-checkbox>
          </div>
        </div>
      </search-box>
      <e-container class="table">
        <a-table
          class="ant-table-striped"
          :columns="Columns"
          :data-source="listData"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
          row-key="id"
          table-layout="fixed"
          :pagination="pageOption"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'tags'">
              <e-tags-field :client="record" />
            </template>
            <template v-if="column.key === 'countryID'">
              <e-country-or-region :code="record.countryID" />
            </template>
            <template v-if="column.key === 'status'">
              <e-client-status :status="record.status"></e-client-status>
            </template>
            <template v-if="column.key === 'fullName'">
              <a-space>
                <a-tooltip>
                  <template #title> Do not contact this client </template>
                  <e-icon v-if="record.fromMLV" type="tips1" fontSize="14px" style="color: #ffaf17; cursor: help" />
                </a-tooltip>
                <a
                  :href="router.resolve({ name: 'Client Detail', params: { id: record.id } }).href"
                  :target="record.id"
                >
                  {{ record.fullName }}
                </a>
              </a-space>
            </template>
          </template>
          <template #emptyText><e-empty /></template>
        </a-table>
      </e-container>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import EContainer from '@/components/EContainer.vue'
import EEmpty from '@/components/EEmpty.vue'
import SearchBox from '@/pages/components/Search.vue'
import ECheckbox from '@/components/ECheckbox.vue'
import TargetClient from '@/api/targetClient.js'
import ECountryRegionSelect from '@/components/ECountryRegionSelect.vue'
import ECountryOrRegion from '@/components/ECountryOrRegion.vue'
import EClientStatus from '@/components/EClientStatus.vue'
import ETagsField from '@/components/ETagsField.vue'
import { useStore } from 'vuex'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import Columns from './columns.js'
import dayjs from 'dayjs'
import { OWNER_AND_ALL_SALES_AT_SAME_TIME } from '@/constants/message.js'
const { message } = inject('Feedback')
// 集团销售总监和销售支持有查看离职销售数据的权限
const hasSalesPermission = computed(() => store.getters['user/isPrimaryCSO'] || store.getters['user/isSalesSupport'])
const loading = ref(true)
const listData = ref([])
const filter = ref({})
const pageOption = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: false,
  onChange(value) {
    this.current = value
    searchStruct.page.pageIndex = value
    loadData()
  }
})
// 两个关联下拉branch/bu和其中的人
const authorities = ref([])
const owners = ref([])
const searchStruct = reactive({
  phaseID: [],
  tier: [],
  status: [],
  clientName: '',
  countryID: 0,
  bumid: -1,
  type: -1,
  empID: -1,
  url: '',
  beginTime: undefined,
  endTime: undefined,
  page: { pageRows: 10, pageIndex: 1, total: 0, sort: undefined, order: undefined },
  ownerBy: ''
})
const disabledDateStart = current => {
  return (searchStruct.endTime ? current > dayjs(searchStruct.endTime) : false) || current > dayjs()
}
const disabledDateEnd = current => {
  return (searchStruct.beginTime ? current < dayjs(searchStruct.beginTime) : false) || current > dayjs()
}
const authorityValue = computed({
  get() {
    return searchStruct.bumid + ':' + searchStruct.type
  },
  set(value) {
    searchStruct.bumid = value.split(':')[0]
    searchStruct.type = value.split(':')[1]
  }
})
const countryIDWrapped = useDictNullValue(searchStruct, 'countryID')
const route = useRoute()
const router = useRouter()
const store = useStore()
store.dispatch('dict/getCountriesOrRegions')
store.dispatch('dict/getClientStatusTypes')
const getAuthority = () => {
  return new Promise(resolve => {
    TargetClient.getAuthority().then(({ data }) => {
      authorities.value = data
      resolve()
    })
  })
}
const getEmployee = () => {
  TargetClient.getEmployee(searchStruct.bumid, searchStruct.type).then(({ data }) => {
    owners.value = data
  })
}
watch(
  () => authorityValue.value,
  () => {
    searchStruct.empID = -1
    getEmployee()
  }
)
const loadConditions = () => {
  return new Promise(resolve => {
    TargetClient.getFilterConditionsAdmin(
      searchStruct.clientName,
      searchStruct.countryID,
      searchStruct.url,
      searchStruct.bumid,
      searchStruct.type,
      searchStruct.empID,
      searchStruct.beginTime,
      searchStruct.endTime,
      searchStruct.ownerBy
    ).then(res => {
      filter.value = reactive(res.data)
      filter.value.clientPhaseLists[0].checked = true
      filter.value.clientStatusLists[0].checked = true
      filter.value.clientTierLists[0].checked = true
      updateSearchStruct()
    })
    resolve()
  })
}
const loadData = () => {
  loading.value = true
  TargetClient.listAdmin(searchStruct)
    .then(res => {
      listData.value = res.data
      pageOption.total = res.total
    })
    .finally(() => {
      loading.value = false
    })
}
getAuthority().then(() => {
  getEmployee()
  loadConditions().then(() => {
    loadData()
  })
})
const updateSearchStruct = () => {
  pageOption.current = 1
  searchStruct.page.pageIndex = 1
  searchStruct.phaseID = filter.value.clientPhaseLists.filter(phase => phase.checked).map(phase => phase.id)
  searchStruct.status = filter.value.clientStatusLists.filter(status => status.checked).map(status => status.id)
  searchStruct.tier = filter.value.clientTierLists.filter(tier => tier.checked).map(tier => tier.id)
}
const handleFilterChange = {
  phase: {
    All: () => {
      const otherOptions = filter.value.clientPhaseLists.filter(phase => phase.id !== -2)
      const allOption = filter.value.clientPhaseLists[0]
      if (allOption.checked) {
        otherOptions.filter(phase => phase.checked !== -2).forEach(phase => (phase.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientPhaseLists.filter(phase => phase.id !== -2)
      const allOption = filter.value.clientPhaseLists[0]
      if (otherOptions.some(phase => phase.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(phase => !phase.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  },
  status: {
    All: () => {
      const otherOptions = filter.value.clientStatusLists.filter(status => status.id !== -2)
      const allOption = filter.value.clientStatusLists[0]
      if (allOption.checked) {
        otherOptions.filter(status => status.checked !== -2).forEach(status => (status.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientStatusLists.filter(status => status.id !== -2)
      const allOption = filter.value.clientStatusLists[0]
      if (otherOptions.some(status => status.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(status => !status.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  },
  tier: {
    All: () => {
      const otherOptions = filter.value.clientTierLists.filter(tier => tier.id !== -2)
      const allOption = filter.value.clientTierLists[0]
      if (allOption.checked) {
        otherOptions.filter(tier => tier.checked !== -2).forEach(tier => (tier.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientTierLists.filter(tier => tier.id !== -2)
      const allOption = filter.value.clientTierLists[0]
      if (otherOptions.some(tier => tier.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(tier => !tier.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  }
}
const handleTableChange = (page, filters, sorter) => {
  searchStruct.page.sort = sorter.order === undefined ? undefined : sorter.columnKey
  searchStruct.page.order = sorter.order === undefined ? undefined : sorter.order.substr(0, sorter.order.length - 3)
  loadData()
}
const handleChangeAuthority = () => {}
const handleSearch = () => {
  if (searchStruct.empID !== -1 && searchStruct.ownerBy !== '') {
    message.warning(OWNER_AND_ALL_SALES_AT_SAME_TIME)
  } else {
    pageOption.current = 1
    searchStruct.page.pageIndex = 1
    loadConditions().then(() => {
      loadData()
    })
  }
}
const handleReset = () => {
  searchStruct.phaseID = [-2]
  searchStruct.tier = [-2]
  searchStruct.status = [-2]
  searchStruct.clientName = ''
  searchStruct.countryID = 0
  searchStruct.bumid = -1
  searchStruct.type = -1
  searchStruct.empID = -1
  searchStruct.beginTime = undefined
  searchStruct.endTime = undefined
  searchStruct.ownerBy = ''
  pageOption.current = 1
  searchStruct.page.pageIndex = 1
  loadConditions().then(() => {
    loadData()
  })
}
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_table';
.page-search-components {
  .filter {
    color: @text-gray;
    .title {
      display: inline-block;
      width: 190px;
    }
    .options {
      display: inline-block;
      margin-left: 16px;
      .e-checkbox {
        &:not(:first-child) {
          margin-left: 32px;
        }
        .count {
          display: inline-block;
          height: 16px;
          line-height: 16px;
          font-size: 12px;
          padding: 0 8px;
          border-radius: 8px;
          background-color: #eaeef5;
          font-weight: bold;
          margin-right: 3px;
          vertical-align: unset;
        }
        &.checked {
          .count {
            background-color: #5982fe;
            color: @white;
          }
        }
      }
    }
  }
  .ant-divider {
    margin: 16px 0;
  }
  .search-item {
    margin-right: 24px;
    width: 240px;
    .ant-select {
      width: 100%;
    }
    .search-text {
      color: rgba(107, 121, 142, 0.85);
      font-size: 14px;
      margin: 6px 0 2px 0;
    }
  }
}
.table {
  margin-top: 24px;
}
</style>
<route lang="yaml">
name: Target Clients
path: /target-clients-m/
meta:
  sort: 0
  roles: isPrimaryCSO, isBranchCSO, isBUM, isSalesSupport
</route>
